<?php


/**
 * 数据返回统一格式
 */
function dr_return_data($code, $msg = '', $data = array()) {
    return array(
        'code' => $code,
        'msg' => $msg,
        'data' => $data,
    );
}

/**
 * 当前URL
 */
function dr_now_url() {

    $pageURL = 'http';
    isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' && $pageURL.= 's';

    $pageURL.= '://';
    if (strpos($_SERVER['HTTP_HOST'], ':') !== FALSE) {
        $url = explode(':', $_SERVER['HTTP_HOST']);
        $url[0] ? $pageURL.= $_SERVER['HTTP_HOST'] : $pageURL.= $url[0];
    } else {
        $pageURL.= $_SERVER['HTTP_HOST'];
    }

    $pageURL.= $_SERVER['REQUEST_URI'] ? $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF'];

    $ci	= &get_instance();
    return $ci->security->xss_clean($pageURL);
}

/**
 * 调用远程数据
 *
 * @param	string	$url
 * @return	string
 */
function dr_catcher_data($url) {

    // fopen模式
    if (ini_get('allow_url_fopen')) {
        $data = @file_get_contents($url);
        if ($data !== FALSE) {
            return $data;
        }
    }

    // curl模式
    if (function_exists('curl_init') && function_exists('curl_exec')) {
        $ch = curl_init($url);
        $data = '';
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    return NULL;
}


/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function dr_safe_replace($string) {
    $string = str_replace('%20', '', $string);
    $string = str_replace('%27', '', $string);
    $string = str_replace('%2527', '', $string);
    $string = str_replace('*', '', $string);
    $string = str_replace('"', '&quot;', $string);
    $string = str_replace("'", '', $string);
    $string = str_replace('"', '', $string);
    $string = str_replace(';', '', $string);
    $string = str_replace('<', '&lt;', $string);
    $string = str_replace('>', '&gt;', $string);
    $string = str_replace("{", '', $string);
    $string = str_replace('}', '', $string);
    return $string;
}

/**
 * 字符截取
 *
 * @param	string	$str
 * @param	intval	$length
 * @param	string	$dot
 * @return  string
 */
function dr_strcut($string, $length, $dot = '...') {

    $charset = 'utf-8';
    if (strlen($string) <= $length) {
        return $string;
    }

    $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
    $strcut = '';

    if (strtolower($charset) == 'utf-8') {
        $n = $tn = $noc = 0;
        while ($n < strlen($string)) {
            $t = ord($string[$n]);
            if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1;
                $n++;
                $noc++;
            } elseif (194 <= $t && $t <= 223) {
                $tn = 2;
                $n += 2;
                $noc += 2;
            } elseif (224 <= $t && $t <= 239) {
                $tn = 3;
                $n += 3;
                $noc += 2;
            } elseif (240 <= $t && $t <= 247) {
                $tn = 4;
                $n += 4;
                $noc += 2;
            } elseif (248 <= $t && $t <= 251) {
                $tn = 5;
                $n += 5;
                $noc += 2;
            } elseif ($t == 252 || $t == 253) {
                $tn = 6;
                $n += 6;
                $noc += 2;
            } else {
                $n++;
            }
            if ($noc >= $length)
                break;
        }
        if ($noc > $length)
            $n -= $tn;
        $strcut = substr($string, 0, $n);
    } else {
        for ($i = 0; $i < $length; $i++) {
            $strcut.= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
        }
    }

    $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

    return $strcut . $dot;
}

/**
 * 清除HTML标记
 *
 * @param	string	$str
 * @return  string
 */
function dr_clearhtml($str) {

    $str = str_replace(
        array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $str
    );

    $str = preg_replace("/\<[a-z]+(.*)\>/iU", "", $str);
    $str = preg_replace("/\<\/[a-z]+\>/iU", "", $str);
    $str = preg_replace("/{.+}/U", "", $str);
    $str = str_replace(array(chr(13), chr(10), '&nbsp;'), '', $str);
    $str = strip_tags($str);

    return trim($str);
}

/**
 * 多语言输出
 *
 * @param	多个参数
 * @return	string|NULL
 */
function fc_lang() {

    $param = func_get_args();
    if (empty($param)) {
        return NULL;
    }

    // 取第一个作为语言名称
    $string = $param[0];
    unset($param[0]);


    $string = $param ? vsprintf($string, $param) : $string;


    return $string;
}


/**
 * 模型内容SEO信息
 *
 * @param	array	$mod
 * @param	array	$cat
 * @param	intval	$page
 * @return	array
 */
function dr_show_seo($data, $page = 1) {

    $seo = array();
    $ci = &get_instance();
    $category = $ci->category;
    $cat = $category[$data['catid']];
    $data['page'] = $page;
    $data['join'] = SITE_SEOJOIN ? SITE_SEOJOIN : '_';
    $data['name'] = $data['catname'] = dr_get_cat_pname(null, $cat, $data['join']);

    $meta_title = $cat['setting']['seo']['show_title'] ? $cat['setting']['seo']['show_title'] : '['.fc_lang('第%s页', '{page}').'{join}]{title}{join}{name}{join}{modulename}{join}{SITE_NAME}';

    $meta_title = $page > 1 ? str_replace(array('[', ']'), '', $meta_title) : preg_replace('/\[.+\]/U', '', $meta_title);

    // 兼容php5.5
    if (version_compare(PHP_VERSION, '5.5.0') >= 0) {
        $rep = new php5replace($data);
        $seo['meta_title'] = preg_replace_callback('#{([a-z_0-9]+)}#U', array($rep, 'php55_replace_data'), $meta_title);
        $seo['meta_title'] = preg_replace_callback('#{([A-Z_]+)}#U', array($rep, 'php55_replace_var'), $seo['meta_title']);
        unset($rep);
    } else {
        extract($data);
        $seo['meta_title'] = preg_replace('#{([a-z_0-9]+)}#Ue', "\$\\1", $meta_title);
        $seo['meta_title'] = preg_replace('#{([A-Z_]+)}#Ue', "\\1", $seo['meta_title']);
    }

    if (is_array($data['keywords'])) {
        foreach ($data['keywords'] as $key => $t) {
            $seo['meta_keywords'].= $key.',';
        }
        $seo['meta_keywords'] = trim($seo['meta_keywords'], ',');
    } else {
        $seo['meta_keywords'] = $data['keywords'];
    }

    $seo['meta_description'] = htmlspecialchars(dr_clearhtml($data['description']));

    return $seo;
}

/**
 * 模型栏目SEO信息
 *
 * @param	array	$mod
 * @param	array	$cat
 * @param	intval	$page
 * @return	array
 */
function dr_category_seo($cat, $page = 1) {

    $seo = array();
    $cat['page'] = $page;
    $cat['join'] = SITE_SEOJOIN ? SITE_SEOJOIN : '_';
    $cat['name'] = $cat['catname'] = dr_get_cat_pname(null, $cat, $cat['join']);

    $meta_title = $cat['setting']['seo']['list_title'] ? $cat['setting']['seo']['list_title'] : '['.fc_lang('第%s页', '{page}').'{join}]{modulename}{join}{SITE_NAME}';

    $meta_title = $page > 1 ? str_replace(array('[', ']'), '', $meta_title) : preg_replace('/\[.+\]/U', '', $meta_title);


    // 兼容php5.5
    if (version_compare(PHP_VERSION, '5.5.0') >= 0) {
        $rep = new php5replace($cat);
        $seo['meta_title'] = preg_replace_callback('#{([a-z_0-9]+)}#U', array($rep, 'php55_replace_data'), $meta_title);
        $seo['meta_title'] = preg_replace_callback('#{([A-Z_]+)}#U', array($rep, 'php55_replace_var'), $seo['meta_title']);
        $seo['meta_keywords'] = preg_replace_callback('#{([a-z_0-9]+)}#U', array($rep, 'php55_replace_data'), $cat['setting']['seo']['list_keywords']);
        $seo['meta_keywords'] = preg_replace_callback('#{([A-Z_]+)}#U', array($rep, 'php55_replace_var'), $seo['meta_keywords']);
        $seo['meta_description'] = preg_replace_callback('#{([a-z_0-9]+)}#U', array($rep, 'php55_replace_data'), $cat['setting']['seo']['list_description']);
        $seo['meta_description'] = preg_replace_callback('#{([A-Z_]+)}#U', array($rep, 'php55_replace_var'), $seo['meta_description']);
        unset($rep);
    } else {
        $seo['meta_title'] = preg_replace('#{([a-z_0-9]+)}#Ue', "\$cat[\\1]", $meta_title);
        $seo['meta_title'] = preg_replace('#{([A-Z_]+)}#Ue', "\\1", $seo['meta_title']);
        $seo['meta_keywords'] = preg_replace('#{([a-z_0-9]+)}#Ue', "\$cat[\\1]", $cat['setting']['seo']['list_keywords']);
        $seo['meta_keywords'] = preg_replace('#{([A-Z_]+)}#Ue', "\\1", $seo['meta_keywords']);
        $seo['meta_description'] = preg_replace('#{([a-z_0-9]+)}#Ue', "\$cat[\\1]", $cat['setting']['seo']['list_description']);
        $seo['meta_description'] = preg_replace('#{([A-Z_]+)}#Ue', "\\1", $seo['meta_description']);
    }

    $seo['meta_description'] = htmlspecialchars(dr_clearhtml($seo['meta_description']));

    return $seo;
}


/**
 * 联动菜单包屑导航
 *
 * @param	string	$code	联动菜单代码
 * @param	intval	$id		id
 * @param	string	$symbol	间隔符号
 * @param	string	$url	url地址格式，必须存在{linkage}，否则返回不带url的字符串
 * @return	string
 */
function dr_linkagepos($code, $id, $symbol = ' > ', $url = NULL) {

    if (!$code || !$id) {
        return NULL;
    }

    $ci	= &get_instance();
    $url = $url ? urldecode($url) : NULL;
    $link = $ci->get_cache('linkage-'.SITE_ID.'-'.$code);
    $cids = $ci->get_cache('linkage-'.SITE_ID.'-'.$code.'-id');
    if (is_numeric($id)) {
        // id 查询
        $id = $cids[$id];
        $data = $link[$id];
    } else {
        // 别名查询
        $data = $link[$id];
    }

    $name = array();
    $pids = @explode(',', $data['pids']);


    foreach ($pids as $pid) {
        $pid && $name[] = $url ? "<a href=\"".str_replace('{linkage}', $cids[$pid], $url)."\">{$link[$cids[$pid]]['name']}</a>" : $link[$cids[$pid]]['name'];
    }
    $name[] = $url ? "<a href=\"".str_replace('{linkage}', $id, $url)."\">{$data['name']}</a>" : $data['name'];


    return implode($symbol, $name);
}

/**
 * 模型栏目面包屑导航
 *
 * @param	intval	$catid	栏目id
 * @param	string	$symbol	面包屑间隔符号
 * @param	string	$url	是否显示URL
 * @param	string	$html	格式替换
 * @return	string
 */
function dr_catpos($catid, $symbol = ' > ', $url = TRUE, $html= '') {

    if (!$catid) {
        return '';
    }

    $html = str_replace(array('[url]', '[name]'), array('{url}', '{name}'), $html);

    $ci	= &get_instance();
    $cat = $ci->category;
    if (!isset($cat[$catid])) {
        return '';
    }

    $name = array();
    $array = explode(',', $cat[$catid]['pids']);
    foreach ($array as $id) {
        if ($id && $cat[$id]) {
            $murl = $cat[$id]['url'];
            $name[] = $url ? ($html ? str_replace(array('{url}', '{name}'), array($murl, $cat[$id]['name']), $html): "<a href=\"{$murl}\">{$cat[$id]['name']}</a>") : $cat[$id]['name'];
        }
    }

    $murl = $cat[$catid]['url'];
    $name[] = $url ? ($html ? str_replace(array('{url}', '{name}'), array($murl, $cat[$catid]['name']), $html): "<a href=\"{$murl}\">{$cat[$catid]['name']}</a>") : $cat[$catid]['name'];

    return implode($symbol, $name);
}

/**
 * 模型栏目层次关系
 *
 * @param	array	$mod
 * @param	array	$cat
 * @param	string	$symbol
 * @return	string
 */
function dr_get_cat_pname($mod, $cat, $symbol = '_') {

    if (!$cat['pids']) {
        return $cat['name'];
    }

    $ci = &get_instance();
    $name = array();
    $array = explode(',', $cat['pids']);
    $category = $ci->category;

    foreach ($array as $id) {
        $id && $category[$id] && $name[] = $category[$id]['name'];
    }

    $name[] = $cat['name'];
    krsort($name);

    return implode($symbol, $name);
}

/**
 * 时间显示函数
 *
 * @param	int		$time	时间戳
 * @param	string	$format	格式与date函数一致
 * @param	string	$color	当天显示颜色
 * @return	string
 */
function dr_date($time = NULL, $format = 'Y-m-d H:i:s', $color = NULL) {

    $time = (int) $time;
    if (!$time) {
        return '';
    }

    $format = $format ? $format : 'Y-m-d H:i:s';
    $string = date($format, $time);
    if (strpos($string, '1970') !== FALSE) {
        return '';
    }

    return $color && $time >= strtotime(date('Y-m-d 00:00:00')) && $time <= strtotime(date('Y-m-d 23:59:59')) ? '<font color="' . $color . '">' . $string . '</font>' : $string;
}

